//
// Created by gj on 16-2-15.
//

#include "com_base_util_jniutils_Base64.h"
#include "log/CLog.h"
#include "base64/base64.h"

static LOG_CREATE_FUNC("Base64")

/*
 * Class:     com_base_util_jniutils_Base64
 * Method:    nativeEncode
 * Signature: ([BII)[B
 */
JNIEXPORT jbyteArray JNICALL Java_com_base_util_jniutils_JniBase64_NATIVE_1ENCODE(JNIEnv *env, jclass clazz, jbyteArray input, jint inSize, jint flags) {
    LOG_I_FUNC("--> start")
    jbyte *_in = env->GetByteArrayElements(input, JNI_FALSE);
    int32_t outSize = base64_encode_buffsize(inSize, flags) + 1;

    uint8_t *_out = new uint8_t[outSize];
    bzero(_out, outSize);

    int32_t retcode = base64_encode((uint8_t *) _in, inSize, (uint8_t *) _out, outSize, flags);

    jbyteArray byArr = NULL;
    if (retcode != BASE64_SUCCESS) {
        LOG_E_FILE_FUNC("retCode --> %d", retcode);
    } else {
        byArr = env->NewByteArray(outSize);
        env->SetByteArrayRegion(byArr, 0, outSize, (jbyte *) _out);
    }
    env->ReleaseByteArrayElements(input, _in, JNI_FALSE);
    delete[] _out;
    return byArr;
}

/*
 * Class:     com_base_util_jniutils_Base64
 * Method:    nativeDecode
 * Signature: ([BI)[B
 */
JNIEXPORT jbyteArray JNICALL Java_com_base_util_jniutils_JniBase64_NATIVE_1DECODE(JNIEnv *env, jclass clazz, jbyteArray input, jint inSize) {
    LOG_I_FUNC("--> start")
    jbyte *_in = env->GetByteArrayElements(input, JNI_FALSE);
    int32_t outSize = base64_decode_buffsize(inSize) + 1;

    uint8_t *_out = new uint8_t[outSize];
    bzero(_out, outSize);

    int32_t retcode = base64_decode((uint8_t *) _in, inSize, (uint8_t *) _out, outSize);

    jbyteArray byArr = NULL;
    if (retcode != BASE64_SUCCESS) {
        LOG_E_FILE_FUNC("retCode --> %d", retcode);
    } else {
        byArr = env->NewByteArray(outSize);
        env->SetByteArrayRegion(byArr, 0, outSize, (jbyte *) _out);
    }
    env->ReleaseByteArrayElements(input, _in, JNI_FALSE);
    delete[] _out;
    return byArr;
}